package com.yto.hrreport.event.buttons {
	import com.adobe.serialization.json.JSON;
	import com.yto.hrreport.command.ReportCommand;
	import com.yto.hrreport.event.buttons.superbutton.ButtonEvent;
	import com.yto.hrreport.pub.IProcessor;
	
	import flash.events.MouseEvent;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.managers.PopUpManager;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.RemoteObject;
	
	public class StatisticButtonEvent extends ButtonEvent {
		
		
		private static var statisticEvent : StatisticButtonEvent = new StatisticButtonEvent();
		private static var parentName : String;
		private var param : Object;
		public function StatisticButtonEvent() {
			super();
		}
		
		public static function getInstance(parentName : String) : StatisticButtonEvent {
			StatisticButtonEvent.parentName = parentName;
			return statisticEvent;
		}
		
		public function statisticHandler(event : MouseEvent) : void {
			
			param = ReportCommand.getInstance(parentName).initParam("onBoStatistic");
			
			var reg : RegExp = /^[0-9][0-9][0-9][0-9]-[0-1][0-9]$/;
			
			if(!reg.test(param.statisticPeriod)) {
				Alert.show("请输入正确的统计期间（格式：4位年-2位月，如：2000-01）" , "提示" , Alert.OK , hrreport.ui);
				return ;
			}
			
			PopUpManager.addPopUp(hrreport.waitWindow, hrreport.ui, true);    
			PopUpManager.centerPopUp(hrreport.waitWindow);
			var tableServer : RemoteObject = new RemoteObject;
			tableServer.destination = IProcessor.TableProcessor;
			tableServer.queryHeadData(parentName , param.statisticPeriod);
			tableServer.addEventListener(ResultEvent.RESULT , isExsits);
			
		}
		
		public function isExsits(event : ResultEvent) : void {
			
			var lastResult : String = event.result as String;
			if(lastResult == null || "" == lastResult || "[]" == lastResult) {
				
				
				var queryServer : RemoteObject = new RemoteObject;
				queryServer.destination = IProcessor.QueryProcessor;
				queryServer.executeQuery(param.statisticPeriod , parentName);
				queryServer.addEventListener(ResultEvent.RESULT , queryResultHandler);
				
			} else {
				
				PopUpManager.removePopUp(hrreport.waitWindow);
				Alert.show("当前填入的期间已经统计，请勿重复统计!" , "提示" , Alert.OK , hrreport.ui);
				
			}
			
			
			
		}
		
		public function queryResultHandler(event : ResultEvent) : void {
			
			var lastResult : String = event.result as String;
			if(lastResult != null && lastResult != "false") {
				var result : Array = JSON.decode(lastResult) as Array;
				var bodyArray : ArrayCollection = new ArrayCollection(result);
				param.bodyGrid.dataProvider = bodyArray;
			} else {
				Alert.show("统计时出现异常..." , "提示" , Alert.OK , hrreport.ui);
			}
			
			PopUpManager.removePopUp(hrreport.waitWindow);
			
		}
	}
}